#include <klib.h>
#include <klib-macros.h>
#include <stdint.h>

#if !defined(__ISA_NATIVE__) || defined(__NATIVE_USE_KLIB__)

size_t strlen(const char *s) {
  size_t i = 0;
  while (*s){
	  s++;
  	  i++;
  }
  return i;
}

char *strcpy(char *dst, const char *src) {
	assert(dst != NULL || src != NULL);
	char *ret = dst;
	while ((*dst++=*src++)!='\0'); 
			
return ret;	
}

char *strncpy(char *dst, const char *src, size_t n) {
	assert((dst != NULL) && (src != NULL));
	if (dst == NULL || src == NULL) return NULL;
	char *strDestcopy = dst;
	while ((n--)&&(*dst++ = *src++) != '\0');
	if (n > 0)                           
	{
		while(--n){
			*dst = '\0';
		}
	}       
return strDestcopy;
}

char *strcat(char *dst, const char *src) {
    assert(dst != NULL && src != NULL);
    char *temp = dst;
    while (*temp != '\0')
	        temp++;
    while ((*temp++ = *src++) != '\0');

    return dst;
}

int strcmp(const char *s1, const char *s2) {
	int ret=0;
	while( !(ret = *(unsigned char*)s1 - *(unsigned char*)s2 ) && *s1 )
	{
		s1++;
		s2++;
	}
	      if(ret < 0) return -1;
	         else if(ret > 0)return 1;
	 return 0;        
}

int strncmp(const char *s1, const char *s2, size_t n) {
	assert(s1 && s2);
	if(!n) return 0;
	while(--n && *s1 && (*s1 == *s2))
	{
		s1++;
		s2++;
	 }
return *s1-*s2;
}

void *memset(void *s, int c, size_t n) {
if (s == NULL || n < 0){
	return NULL;
}
char *pdst = (char *)s;
while(n-- > 0)
	*pdst++ = c;
return s;
}

void *memmove(void *dst, const void *src, size_t n) {
 assert (dst != NULL && src != NULL);
 void *rest = dst;
 if(dst < src){
 	while(n--){
	*(char *)dst = *(char *)src;
	(char *)dst++;
	(char *)src++;
	}
 }
 else{
 	while(n--){
	 *((char*)dst + n) = *((char*)src + n);	
	}
 }
return rest;
}

void *memcpy(void *out, const void *in, size_t n) {
	if (out == NULL || in == NULL || n <= 0)
	return NULL;
	char * pdst = (char *)out;
	char * psrc = (char *)in;
	if (pdst > psrc && pdst < psrc + n)
	{
		pdst = pdst + n - 1;
		psrc = psrc + n - 1;
		while (n--)
		*pdst-- = *psrc--;
	}
	else
	{
		while (n--)
		*pdst++ = *psrc++;
	}
return out;		    
}

int memcmp(const void *s1, const void *s2, size_t n) {
	assert(s1!=NULL && s2!=NULL && n>0);
	const char *pdest=(char*)s1;
	const char *psrc=(char*)s2;
	while(*pdest == *psrc && --n>0)
	{
		pdest++;						               
		psrc++;
	}	               
	int a=*pdest-*psrc;
				               if(a>0){return 1;}
					               else if(a<0){return -1;}
						               else{return 0;}
}

#endif
